using System;
using System.Collections.Generic;
using System.Text;
using OpenComposite.Base.Designer;
using System.Drawing.Drawing2D;
using OpenComposite.EII.Repository;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using OpenComposite.EII.CodeGenerators;
using OpenComposite.EII.Services;
using System.Diagnostics;
using OpenComposite.Base.Collections;

namespace OpenComposite.EII.Designer.SCA
{
	public class CompositeReferenceSymbol : CollapsableSymbol, IRepositoryItemSymbol
	{
		#region Initialization
		/// <summary>
		/// Initializes a new instance of the CompositeReferenceSymbol class.
		/// </summary>
		public CompositeReferenceSymbol()
		{
			init();
		}
		private void init()
		{
			this.BeginUpdate();

			this.Border = BorderType.RoundedRectangle;
			this.BorderColor = Color.Black;
			this.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
			this.BorderWidth = 2;

			this.BackColor = Color.FromArgb(64, Color.LemonChiffon);
			this.BackBrushMode = BackgroundBrushMode.LinearGradient;
			this.BackLinearGradientMode = LinearGradientMode.ForwardDiagonal;

			//this.Name = "serviceModuleSymbol" + GetCount(typeof(ServiceModuleSymbol));
			this.Text = "Composite";

			this.Size = new Size(600, 300);
			this.MinimumSize = new Size(70, 50);

			this.UseCustomCollapseClick = true;
			this.CustomCollapseButtonClick += new EventHandler(CompositeReferenceSymbol_CustomCollapseButtonClick);

			this.NameTextBox.AutoSize = false;
			this.NameTextBox.Width = this.NameTextBox.Width - 20;

			this.CollapsedSize = new Size(130, 80);
			this.CollapsedBorderColor = Color.Black;
			this.CollapsedBackColor = Color.FromArgb(255, 153, 1);
			this.CollapsedBackColor2 = Color.White;
			this.ExpandedSize = new Size(600, 300);
			this.ExpandedBorderColor = Color.Black;
			this.ExpandedBackColor = Color.FromArgb(64, 121, 137, 251);
			this.ExpandedBackColor2 = Color.FromArgb(64, 121, 137, 251);

			//
			// this.ContextMenuStrip
			//
			this.ContextMenuStrip = new ContextMenuStrip();
			//this.ContextMenuStrip.Items.Add("Open Orchestration", null, new EventHandler(context_OpenOrchestration)).Name = "openorchestration";
			this.ContextMenuStrip.Items.Add("Open Composite", null, new EventHandler(context_Open)).Name = "opencomposite";
			this.ContextMenuStrip.Items.Add(new ToolStripSeparator());
			//this.ContextMenuStrip.Items.Add("Deploy Composite", Properties.Resources.PublishToWeb, new EventHandler(context_Deploy)).Name = "deploycomposite";
			//this.ContextMenuStrip.Items["deploycomposite"].ImageTransparentColor = Color.Magenta;
			//this.ContextMenuStrip.Items.Add(new ToolStripSeparator());
			this.ContextMenuStrip.Items.Add("Remove Composite", null, new EventHandler(context_Remove));
			this.ContextMenuStrip.Items.Add("Delete Composite", OpenComposite.Repository.Properties.Resources.ico_delete_16x.ToBitmap(), new EventHandler(context_Delete));
			this.ContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(ContextMenuStrip_Opening);

			//_item = null;

			//
			// Interfaces and References
			//
			_interfaces = new List<InterfaceSymbol>();
			_references = new List<ReferenceSymbol>();

			this.IsCollapsed = true;

			this.EndUpdate();
		}

		#endregion

		#region Public Members

		#region Properties
		public override bool CanSelect
		{
			get { return true; }
		}
		public override bool CanFocused
		{
			get { return true; }
		}
		public override bool CanMove
		{
			get { return true; }
		}
		public override bool CanResize
		{
			get { return true; }
		}
		public override bool IsContainer
		{
			get { return true; }
		}
		public override bool NoClip
		{
			get { return false; }
		}
		#endregion

		#region Override
		public override object GetDragObject(Point location, MouseButtons button)
		{
			return this;
		}
		public override void DropObject(object obj, Point location, MouseButtons button)
		{
			RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			if ( repSvc == null )
				throw new NullReferenceException("RepositoryService not available.");

			if ( this.IsCollapsed )
				return;

			if ( this.IsDropAllowed(obj, location, button) ) {
				if ( button == MouseButtons.Left ) {
					if ( obj is InterfaceSymbol ) {
						AddInterfaceSymbol((InterfaceSymbol)obj);
					} else if ( obj is ReferenceSymbol ) {
						AddReferenceSymbol((ReferenceSymbol)obj);
					} else {
						bool isAdded = false;
						DesignerControl dc = null;
						if ( obj is RepositoryItemBase ) {
							if ( obj is Repository.ServiceModule ) {
								Repository.ServiceModule svcmodule = obj as Repository.ServiceModule;
								List<DesignerControl> lstDCtrls =
									this.DesignerViewControl.LoadDiagramFromXmlAndGetTopControls(
										svcmodule.Diagram,
										this.DesignerViewControl.Types);
								if ( lstDCtrls.Count > 0 ) {
									dc = lstDCtrls[0];
									dc.Location = this.PointToDesignerControlClient(location);
									IRepositoryItemSymbol repsym = dc as IRepositoryItemSymbol;
									if ( repsym != null )
										repsym.IsReference = true;
									this.Controls.Add(dc);
									if ( this.DesignerViewControl.DesignController is DesignController )
										( (DesignController)this.DesignerViewControl.DesignController ).ReloadItems(dc);
									isAdded = true;
								}
							} else {
								( (RepositoryItemBase)obj ).Reload();
								dc = repSvc.CreateDesignerControl((RepositoryItemBase)obj);
							}
							if ( dc is CollapsableSymbol ) {

								( (CollapsableSymbol)dc ).IsCollapsed = true;
								( (CollapsableSymbol)dc ).UseCustomCollapseClick = true;
							}
						} else {
							dc = obj as DesignerControl;
						}
						if ( !isAdded && dc != null ) {
							dc.Location = this.PointToDesignerControlClient(location);
							this.Controls.Add(dc);
						}
					}
				} else {
					this.DesignerViewControl.AddRoute((DesignerControl)obj, this);
				}
			}
		}
		public override bool IsDropAllowed(object obj, Point location, MouseButtons button)
		{
			if ( this.IsCollapsed )
				return false;

			#region old code
			//if ( obj == this )
			//    return false;
			//if ( obj is Repository.ServiceModule &&
			//    ( (Repository.ServiceModule)obj ).ID == ( this.RepositoryItem != null ? this.RepositoryItem.ID : 0 ) )
			//    return false;
			#endregion

			return IsDropAllowed(obj.GetType(), location, button);
		}
		public override bool IsDropAllowed(Type type, Point location, MouseButtons button)
		{
			if ( this.IsCollapsed )
				return false;
			#region old code
			//if ( ( type == typeof(InterfaceSymbol) ||
			//       type == typeof(ReferenceSymbol) ||
			//       type == typeof(ServiceComponentSymbol) ||
			//       type.IsSubclassOf(typeof(ServiceComponentSymbol)) ||
			//       type == typeof(StandaloneReferenceSymbol) ||
			//       type == typeof(Selector.SelectorSymbol) ||
			//       type == typeof(ServiceModuleSymbol) ||
			//       type == typeof(Generic.MappingSymbol) ||
			//       type == typeof(Repository.Service) ||
			//       type == typeof(Repository.ServiceModule) ) &&
			//      button == MouseButtons.Left )
			//    return true;
			//else if ( ( type == typeof(BusinessServices.BusinessServiceSymbol) ||
			//            type == typeof(ServiceModuleSymbol) ||
			//            type == typeof(InterfaceSymbol) ) && button == MouseButtons.Right )
			//    return true;
			#endregion
			else
				return false;
		}

		public override bool CreateRouteEnd(DesignerControl controlStart, out IConnector connector,
			out System.Drawing.Drawing2D.LineCap cap, out System.Drawing.Drawing2D.CustomLineCap customcap,
			out RouteDockDirection dockStart, out RouteDockDirection dockEnd,
			out bool useEndConnectorAsRouteEnd)
		{
			bool ok = base.CreateRouteEnd(controlStart, out connector, out cap, out customcap, out dockStart, out dockEnd, out useEndConnectorAsRouteEnd);

			cap = System.Drawing.Drawing2D.LineCap.Custom;
			GraphicsPath path = new GraphicsPath();
			path.AddEllipse(-2.5f, -2.5f, 5f, 5f);
			customcap = new System.Drawing.Drawing2D.CustomLineCap(path, null);

			return ok;
		}

		public override void ReadXml(System.Xml.XmlReader reader)
		{
			RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			if ( repSvc == null )
				throw new NullReferenceException("RepositoryService not available.");

			System.ComponentModel.BooleanConverter bc = new System.ComponentModel.BooleanConverter();
			try {
				while ( reader.Read() ) {
					switch ( reader.Name ) {
						case "DesignerControl":
							if ( reader.NodeType == System.Xml.XmlNodeType.EndElement ) {
								return;
							}
							break;
						case "ServiceModule":
							if ( reader.MoveToAttribute("id") && reader.ReadAttributeValue() )
								this.RepositoryItem = repSvc.GetItem(ItemType.Composite, int.Parse(reader.Value), false);
							if ( reader.MoveToAttribute("isMainControl") && reader.ReadAttributeValue() )
								if ( reader.Value == true.ToString() && this.DesignerViewControl != null )
									this.DesignerViewControl.MainControl = this;
							if ( reader.MoveToAttribute("isRef") && reader.ReadAttributeValue() )
								this.IsReference = (bool)bc.ConvertFromString(reader.Value);
							break;
						case "DesignerControls":
							// read child controls
							ReadChildControls(reader);
							break;
						default:
							ReadStandardProperties(reader);
							break;
					}
				}
			} finally {
				if ( _interfaces.Count > 0 ) {
					foreach ( InterfaceSymbol i in _interfaces ) {
						i.Remove();
					}
					_interfaces.Clear();
				}
				if ( _references.Count > 0 ) {
					foreach ( ReferenceSymbol r in _references ) {
						r.Remove();
					}
					_references.Clear();
				}
				foreach ( DesignerControl dc in this.Controls ) {
					if ( dc is InterfaceSymbol )
						_interfaces.Add((InterfaceSymbol)dc);
					else if ( dc is ReferenceSymbol )
						_references.Add((ReferenceSymbol)dc);
				}
			}
			if ( this.RepositoryItem == null ) {
				this.Remove();
			}
		}
		internal void ReadXmlForDroppedItem(System.Xml.XmlReader reader)
		{
			try {
				while ( reader.Read() ) {
					switch ( reader.Name ) {
						case "DesignerControl":
							if ( reader.NodeType == System.Xml.XmlNodeType.EndElement ) {
								return;
							}
							break;
						case "DesignerControls":
							// read child controls
							ReadChildControls(reader);
							break;
						default:
							ReadStandardProperties(reader);
							break;
					}
				}
			} finally {
				if ( _interfaces.Count > 0 ) {
					while ( _interfaces.Count > 0 ) {
						_interfaces[0].Remove();
					}
					_interfaces.Clear();
				}
				if ( _references.Count > 0 ) {
					while ( _references.Count > 0 ) {
						_references[0].Remove();
					}
					_references.Clear();
				}
				foreach ( DesignerControl dc in this.Controls ) {
					if ( dc is InterfaceSymbol )
						_interfaces.Add((InterfaceSymbol)dc);
					else if ( dc is ReferenceSymbol )
						_references.Add((ReferenceSymbol)dc);
				}
			}
		}
		public override void WriteXml(System.Xml.XmlWriter writer)
		{
			System.ComponentModel.BooleanConverter bc = new System.ComponentModel.BooleanConverter();
			WriteStandardProperties(writer);

			if ( _item != null ) {
				writer.WriteStartElement("ServiceModule");
				writer.WriteAttributeString("id", _item.ID.ToString());
				writer.WriteAttributeString("name", _item.Name);
				writer.WriteAttributeString("isMainControl", bc.ConvertToString(false));
				writer.WriteAttributeString("isRef", bc.ConvertToString(this.IsReference));
				writer.WriteEndElement();
			}

			WriteChildControls(writer);
		}

		public override void InitializeNew(IServiceProvider serviceProvider)
		{
			RepositoryService repSvc = (RepositoryService)serviceProvider.GetService(typeof(RepositoryService));
			if ( repSvc == null )
				throw new NullReferenceException("RepositoryService not available.");

			base.InitializeNew(serviceProvider);

			IRepositoryChangeService svc = serviceProvider.GetService(typeof(IRepositoryChangeService)) as IRepositoryChangeService;
			if ( svc != null ) {
				svc.RepositoryChanged += new RepositoryChangedEventHandler(svc_RepositoryChanged);
			}
			//AddInterfaceSymbol(repSvc.CreateDesignerControl(ItemType.SCA_Export, false) as InterfaceSymbol);
		}
		public override void InitializeLoaded()
		{
			base.InitializeLoaded();
			IRepositoryChangeService svc = this.GetService(typeof(IRepositoryChangeService)) as IRepositoryChangeService;
			if ( svc != null ) {
				svc.RepositoryChanged += new RepositoryChangedEventHandler(svc_RepositoryChanged);
			}
		}

		public override object GetService(Type serviceType)
		{
			if ( _item != null )
				return _item.GetService(serviceType);
			else
				return base.GetService(serviceType);
		}
		#endregion

		#region IRepositoryItemSymbol Members

		public bool SaveHierarchy
		{
			get { return false; }
		}

		private bool _isReference = false;
		public bool IsReference
		{
			get { return _isReference; }
			set { _isReference = value; }
		}

		public bool CanBeMainControl
		{
			get { return true; }
		}

		public OpenComposite.EII.Repository.IRepositoryItem RepositoryItem
		{
			get
			{
				return _item;
			}
			set
			{
				if ( value is ServiceModule ) {
					_item = value as ServiceModule;
					doItemChanged();
				} else {
					_item = null;
				}
			}
		}

		public void Load(int idRepository, int idDomain)
		{
			RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			if ( repSvc == null )
				throw new NullReferenceException("RepositoryService not available.");

			BindingListEx<Verb> verbs = _item.GetVerbs();
			if ( verbs != null && verbs.Count > 0 ) {
				foreach ( DesignerControl dc in this.Controls ) {
					ExposedCapabilitySymbol e = dc as ExposedCapabilitySymbol;
					if ( e != null ) {
						e.ServiceModule = _item;
						return;
					}
				}
				ExposedCapabilitySymbol newECS = new ExposedCapabilitySymbol();
				newECS.Collapse();
				newECS.ServiceModule = _item;

				int x = -( newECS.Width / 2 ) - 5;
				int y = ( this.ClientRectangle.Height / 2 ) - ( newECS.Height / 2 );// ( this.IsCollapsed ? 20 : 40 );

				newECS.Location = new Point(x, y);
				newECS.Removed += new EventHandler(symbol_Removed);

				//if ( _exposedCapability != null ) this.Controls.Remove(_exposedCapability);
				this.Controls.Add(newECS);
				//_exposedCapability = symbol;
			}
		}
		public bool Save(int idRepository, int idDomain)
		{
			if ( _item == null )
				return false;

			return _item.Save();
		}

		public bool Delete(bool bAsk)
		{
			if ( _item == null )
				return true;

			return _item.Delete(bAsk);
		}

		#endregion

		#endregion

		#region Protected Members

		protected bool disableCollapseExpandReposition = false;

		#region Methods
		protected void AddInterfaceSymbol(InterfaceSymbol symbol)
		{
			if ( this.IsCollapsed )
				symbol.Collapse();
			else
				symbol.Expand();

			int x = -( symbol.Width / 2 ) - 5;
			//int y = ( this.IsCollapsed ? 20 : 40 );
			//if ( _interfaces.Count > 0 )
			//    y = _interfaces[_interfaces.Count - 1].Bottom + ( this.IsCollapsed ? 10 : 20 );
			int y = ( this.ClientRectangle.Height / ( _interfaces.Count + 2 ) ) - ( symbol.Height / 2 );

			symbol.Anchor = AnchorStyles.Left;
			symbol.Location = new Point(x, y);
			symbol.Removed += new EventHandler(symbol_Removed);
			this.Controls.Add(symbol);
			_interfaces.Add(symbol);
		}

		protected void AddReferenceSymbol(ReferenceSymbol symbol)
		{
			if ( this.IsCollapsed )
				symbol.Collapse();
			else
				symbol.Expand();

			int x = this.ClientRectangle.Width - ( symbol.Width / 2 ) + 10;
			int y = ( this.IsCollapsed ? 20 : 40 );
			if ( _references.Count > 0 )
				y = _references[_references.Count - 1].Bottom + ( this.IsCollapsed ? 10 : 20 );

			symbol.Location = new Point(x, y);
			symbol.Anchor = AnchorStyles.Top | AnchorStyles.Right;
			symbol.Removed += new EventHandler(symbol_Removed);
			this.Controls.Add(symbol);
			_references.Add(symbol);
		}
		protected void Expand()
		{
			this.BeginUpdate();
			for ( int i = 0; i < _interfaces.Count; i++ ) {
				_interfaces[i].Expand();
				_interfaces[i].Location = new Point(-( _interfaces[i].Width / 2 ) - 5,
													40 + ( ( _interfaces[i].Height + 20 ) * i ));
			}
			for ( int i = 0; i < _references.Count; i++ ) {
				_references[i].Expand();
				_references[i].Location = new Point(this.ClientRectangle.Width - ( _references[i].Width / 2 ) + 10,
													40 + ( ( _references[i].Height + 20 ) * i ));
			}
			repositionSiblings(true);
			this.EndUpdate();
		}
		protected void Collapse()
		{
			this.BeginUpdate();
			for ( int i = 0; i < _interfaces.Count; i++ ) {
				_interfaces[i].Visible = true;
				_interfaces[i].Collapse();
				_interfaces[i].Location = new Point(-( _interfaces[i].Width / 2 ) - 5,
													20 + ( ( _interfaces[i].Height + 10 ) * i ));
			}
			for ( int i = 0; i < _references.Count; i++ ) {
				_references[i].Visible = true;
				_references[i].Collapse();
				_references[i].Location = new Point(this.ClientRectangle.Width - ( _references[i].Width / 2 ) + 10,
													20 + ( ( _references[i].Height + 10 ) * i ));
			}
			repositionSiblings(false);
			this.EndUpdate();
		}
		#endregion

		#region Override
		protected override Region GetMouseOverArea()
		{
			Region region = base.GetMouseOverArea();
			foreach ( InterfaceSymbol i in _interfaces ) {
				region.Union(i.GetPaintBounds());
			}
			foreach ( ReferenceSymbol r in _references ) {
				region.Union(r.GetPaintBounds());
			}
			return region;
		}
		protected override void OnTextChanged(EventArgs e)
		{
			if ( _item != null ) {
				_item.Name = this.Text;
				this.Name = this.Text;
			}
			base.OnTextChanged(e);
		}
		protected override void OnCollapsing(System.ComponentModel.CancelEventArgs e)
		{
			base.OnCollapsing(e);
		}
		protected override void OnExpanding(System.ComponentModel.CancelEventArgs e)
		{
			base.OnExpanding(e);
		}
		protected override void OnCollapsed(EventArgs e)
		{
			base.OnCollapsed(e);
			Collapse();
		}
		protected override void OnExpanded(EventArgs e)
		{
			base.OnExpanded(e);
			Expand();
		}

		protected override void OnModeChanged(EventArgs e)
		{
			bool bIsITMode = ( this.Mode == RepositoryModes.ITMode && this == this.DesignerViewControl.MainControl );
			this.ContextMenuStrip.Items[0].Enabled = !bIsITMode;
		}

		protected override void OnControlAdded(DesignerControl ctrl)
		{
			if ( this.IsCollapsed && !( ctrl is InterfaceSymbol || ctrl is ReferenceSymbol || ctrl is ExposedCapabilitySymbol ) )
				ctrl.Visible = false;
		}
		protected override void OnVisibleChanged()
		{
			this.BeginUpdate();
			foreach ( DesignerControl dc in this.Controls ) {
				if ( !( this.IsCollapsed && this.Visible ) ||
					  ( dc == this.NameTextBox || dc == this.CollapseButton ||
						dc is InterfaceSymbol || dc is ReferenceSymbol ) ) {
					dc.Visible = this.Visible;
					if ( dc == this.CollapseButton && !this.ShowCollapseButton )
						dc.Visible = false;
				}
			}
			this.EndUpdate();
		}

		protected override void SetNameTextboxBounds(bool isCollapsed)
		{
			Rectangle rclient = this.ClientRectangle;
			if ( isCollapsed ) {
				this.NameTextBox.Bounds = new Rectangle(10, 0, rclient.Width - 10 - 20, (int)( rclient.Height / 2 ));
				this.NameTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom;
			} else {
				this.NameTextBox.Bounds = new Rectangle(0, 0, rclient.Width - 20, 15);
				this.NameTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
			}
		}

		#endregion

		#endregion

		#region Private Members

		#region Variables
		private ServiceModule _item;
		private List<InterfaceSymbol> _interfaces;
		private List<ReferenceSymbol> _references;
		#endregion

		#region Methods
		private void doItemChanged()
		{
			if ( _item != null ) {
				this.Text = _item.Name;
			}
		}
		private void deployComposite()
		{
			string path = null;
			string errormsg = "";
			Deployment deployment = new Deployment(this);
			foreach ( DesignerControl dc in this.Controls ) {
				if ( dc is OrchestrationComponentSymbol ) {
					OrchestrationComponentSymbol wfsymbol = (OrchestrationComponentSymbol)dc;
					if ( wfsymbol.ProcessOperation != null ) {
						BindingListEx<Repository.Workflow> lstWF = Global.Data.GetOperationWorkflow(wfsymbol.ProcessOperation.ID);
						if ( lstWF != null ) {
							foreach ( Repository.Workflow wf in lstWF ) {
								if ( string.IsNullOrEmpty(path) ) {
									FolderBrowserDialog dlgSelectFolder = new FolderBrowserDialog();
									dlgSelectFolder.Description = "Select a folder to deploy the orchestration.";
									dlgSelectFolder.RootFolder = System.Environment.SpecialFolder.MyComputer;
									if ( dlgSelectFolder.ShowDialog() != DialogResult.OK )
										return;
									path = dlgSelectFolder.SelectedPath;
								}
								try {
									deployment.DeployWorkflow(path, wf, false);
								} catch ( Exception ex ) {
									errormsg += string.Format("{0}{1}", ex.Message, Environment.NewLine);
								}
							}
						}
					}
				}
			}
			if ( !string.IsNullOrEmpty(errormsg) ) {
				MessageBox.Show(errormsg, "Deploy " + this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
			} else {
				MessageBox.Show("Composite Successfully Deployed.", "Deploy " + this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
		}
		private void openDiagram()
		{
			//DesignController dc = this.DesignerViewControl.DesignController as DesignController;
			//if ( dc != null ) {
			//    dc.OpenDiagram(this.RepositoryItem);
			//}
			if ( _item != null ) {
				IMainController mc = this.GetService(typeof(IMainController)) as IMainController;
				if ( mc != null ) mc.OpenDiagram(_item);
			}
		}
		//private void openCompositeOrchestration()
		//{
		//    Repository.Workflow wf = null;
		//    if ( _item.WorkflowID > 0 ) {
		//        wf = _item.Workflow;
		//    } else {
		//        RepositoryService rs = _item.GetService(typeof(RepositoryService)) as RepositoryService;
		//        Debug.Assert(rs!=null);
		//        // config start operation
		//        //DesignController dc = this.DesignerViewControl.DesignController as DesignController;
		//        //FormCreateProcess frm;
		//        //if ( dc != null )
		//        //    frm = new FormCreateProcess(dc);
		//        //else
		//        //    frm = new FormCreateProcess(_item);
		//        //frm.Text = "Define Start Capability";
		//        //frm.ProcessName = "Start";
		//        //frm.ProcessDescription = "This is the start capability of the orchestration.";
		//        //if ( frm.ShowDialog() != DialogResult.OK ) {
		//        //    // cancel
		//        //    return;
		//        //}
		//        Repository.IRepositoryItem parentItem = null;
		//        wf = rs.GetNewItem<Repository.Workflow>(false, ref parentItem);
		//        wf.Name = _item.Name;
		//        wf.Description = _item.Description;
		//        wf.Type = WorkflowType.Orchestration;
		//        wf.BuildType = WorkflowBuildType.ASMX_IIS;
		//        //wf.StartName = frm.ProcessName;
		//        //wf.StartDescription = frm.ProcessDescription;
		//        //wf.InputBusinessObject = frm.InputBusinessObject;
		//        //wf.OutputBusinessObject = frm.OutputBusinessObject;
		//        wf.Save();
		//        Global.Data.AddRepositoryItemToDomainFolder(Global.Status.CurrentDomainId, wf);
		//        _item.WorkflowID = wf.ID;
		//        _item.Save();
		//    }
		//    if ( wf != null ) {
		//        //DesignController dc = this.DesignerViewControl.DesignController as DesignController;
		//        //if ( dc != null )
		//        //    dc.OpenDiagram(wf);
		//        IMainController mc = this.GetService(typeof(IMainController)) as IMainController;
		//        if ( mc != null ) mc.OpenDiagram(wf);
		//    }
		//}
		private void repositionSiblings(bool bExpand)
		{
			Size szChange = this.ExpandedSize - this.CollapsedSize;
			IEnumerator controls = null;
			if ( this.Parent != null ) {
				controls = this.Parent.Controls.GetEnumerator();
			} else if ( this.DesignerViewControl != null ) {
				controls = this.DesignerViewControl.DesignerControls.ControlsWithoutRoutes.GetEnumerator();
			}
			if ( controls != null ) {
				while ( controls.MoveNext() ) {
					DesignerControl dc = controls.Current as DesignerControl;
					if ( dc is CollapseButton )
						continue;
					if ( dc != null ) {
						if ( dc.Left > this.Left ) {
							if ( bExpand )
								dc.Left += szChange.Width;
							else
								dc.Left -= szChange.Width;
						} else if ( dc.Top > this.Top && dc.Right > this.Left ) {
							if ( bExpand )
								dc.Top += szChange.Height;
							else
								dc.Top -= szChange.Height;
						}
					}
				}
			}
			#region old code
			//int iCurrent = 0;
			//List<DesignerControl> listMove = new List<DesignerControl>();
			//DesignerControl dcCurrent = this;
			//Size szChange = this.ExpandedSize - this.CollapsedSize;
			//while ( dcCurrent != null ) {
			//    ServiceModuleSymbol module = dcCurrent as ServiceModuleSymbol;
			//    if ( module != null ) {
			//        foreach ( ReferenceSymbol refsymbol in module._references ) {
			//            listMove.Add(refsymbol.Interface.Parent);
			//            refsymbol.Interface.Parent.Left += szChange.Width;
			//        }
			//    }
			//    if ( listMove.Count > iCurrent ) {
			//        dcCurrent = listMove[iCurrent];
			//        iCurrent++;
			//    } else {
			//        dcCurrent = null;
			//    }
			//}
			#endregion
		}
		#endregion

		#region Event Handlers
		private void CompositeReferenceSymbol_CustomCollapseButtonClick(object sender, EventArgs e)
		{
			// REMOVED: RE 13.12.2007: orchestration designer changed to tabbed view
			//			that contains the composite view
			//			we don't need the separate composite view any more

			//if ( _item.WorkflowID > 0 ) {
			//    ContextMenuStrip cms = new ContextMenuStrip();
			//    cms.Items.Add("Open Orchestration", null, new EventHandler(context_OpenOrchestration));
			//    cms.Items.Add("Open Composite", null, new EventHandler(context_Open));
			//    Point pt = new Point(this.CollapseButton.Right, this.CollapseButton.Bottom);
			//    cms.Show(this.DesignerViewControl.PointToScreen(this.PointToDesignerView(pt)));
			//} else {
			//this.DesignerViewControl.BeginInvoke(new MethodInvoker(openCompositeOrchestration));
			//}
			this.DesignerViewControl.BeginInvoke(new MethodInvoker(openDiagram));
		}

		private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
		{
			//if ( _item.WorkflowID > 0 ) {
			//    this.ContextMenuStrip.Items["openorchestration"].Text = "Open Orchestration";
			//    this.ContextMenuStrip.Items["opencomposite"].Text = "Open Composite";
			//    this.ContextMenuStrip.Items["opencomposite"].Visible = true;
			//} else {
			//    this.ContextMenuStrip.Items["openorchestration"].Text = "Create Orchestration";
			//    this.ContextMenuStrip.Items["opencomposite"].Visible = false;
			//}
		}

		private void context_Remove(object sender, EventArgs e)
		{
			this.Remove();
		}
		private void context_Delete(object sender, EventArgs e)
		{
			if ( this.Delete(true) )
				this.Remove();
		}
		//private void context_Deploy(object sender, EventArgs e)
		//{
		//    //deployComposite();
		//}
		private void context_Open(object sender, EventArgs e)
		{
			this.DesignerViewControl.BeginInvoke(new MethodInvoker(openDiagram));
			// CHANGED: RE 13.12.2007: we renamed orchestrations/business processes
			//			to composites/composite application in the repository tree
			//this.DesignerViewControl.Invoke(new MethodInvoker(openCompositeOrchestration));
		}
		//private void context_OpenOrchestration(object sender, EventArgs e)
		//{
		//    this.DesignerViewControl.Invoke(new MethodInvoker(openCompositeOrchestration));
		//}
		private void symbol_Removed(object sender, EventArgs e)
		{
			if ( sender is ReferenceSymbol )
				_references.Remove((ReferenceSymbol)sender);
			else if ( sender is InterfaceSymbol )
				_interfaces.Remove((InterfaceSymbol)sender);
		}

		private void svc_RepositoryChanged(object sender, RepositoryChangedEventArgs e)
		{
			if ( e.RepositoryItem == (IRepositoryItem)this.RepositoryItem &&
				 e.Member.Name.StartsWith("AddRepositoryHierarchy") ) {
				this.Load(Global.Status.CurrentRepositoryId, Global.Status.CurrentDomainId);
			}
		}

		#endregion

		#endregion
	}
}
